import { debounce } from 'lodash'
class resizeObserver extends window.ResizeObserver {
	constructor(callback) {
		callback = debounce(callback, 100)
		super(callback)
	}
}
class error extends window.Error {
	constructor(params, ...args) {
		const [key = 'message'] = args
		if (
			params &&
			typeof params === 'object' &&
			typeof key === 'string' &&
			params[key]
		) {
			super(params[key])
			for (let param in params) {
				if (param !== key) {
					this[param] = params[param]
				}
			}
			this.type = params.type || 'CustomError'
			this.date = new Date()
		} else {
			super(...arguments)
		}
	}
}
class date extends window.Date {
	constructor(option, ...args) {
		if (typeof option === 'string' && args.length === 0) {
			super(Date.parse(option.replace(/-/g, '/')))
		} else {
			super(...arguments)
		}
	}
	format(fmt) {
		const o = {
			'M+': this.getMonth() + 1, // 月份
			'D+': this.getDate(), // 日
			'h+': this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, // 小时
			'H+': this.getHours(), // 小时
			'm+': this.getMinutes(), // 分
			's+': this.getSeconds(), // 秒
			'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
			S: this.getMilliseconds(), // 毫秒
			W: ['日', '一', '二', '三', '四', '五', '六'][this.getDay()], // 星期
			a: this.getHours() < 12 ? '上午' : '下午', // 上午/下午
			A: this.getHours() < 12 ? 'AM' : 'PM', // AM/PM
		}
		if (/(y+)/.test(fmt) || /(Y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		for (let k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
			}
		}
		return fmt
	}
}

Array.prototype.groupBy = function (callback) {
	let groups = {};
	this.forEach(o => {
		let group = JSON.stringify(callback(o));
		groups[group] = groups[group] || [];
		groups[group].push(o);
	});
	return Object.keys(groups).map(group => {
		return groups[group];
	});
}
window.Date = date
window.Error = error
window.ResizeObserver = resizeObserver